package org.ishequ.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.ishequ.adapter.PersonAdapter;
import org.ishequ.domain.Person;
import org.ishequ.service.PersonService;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Android_DBActivity extends Activity {
	private ListView listView;
	private PersonService personService;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        
        personService = new PersonService(getApplicationContext());
        listView = (ListView)findViewById(R.id.listview);
        listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ListView lview = (ListView) parent;
				Person person = (Person)lview.getItemAtPosition(position);//show 返回的是Map show2 返回的是Cursor show3返回的是Person
				Toast.makeText(getApplicationContext(), person.getName(), Toast.LENGTH_SHORT).show();
			}
        	
        });
        showlist3();
    }
	
	/**自定义adapter**/
	public void showlist3(){
		List<Person> persons = personService.getScrollData(0, 20);
		PersonAdapter adapter = new PersonAdapter(this, R.layout.item, persons);
		listView.setAdapter(adapter);
	}
	
	private void showlist2(){
		Cursor cursor = personService.getCursorScrollData(0, 20);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,new String[]{"name","phone","amount"}, new int[]{R.id.name,R.id.phone,R.id.amount});
		listView.setAdapter(adapter);
	}

	private void showlist() {
		List<Person> persons = personService.getScrollData(0, 20);
		List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>();
		for(Person person : persons){
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("name", person.getName());
			map.put("phone", person.getPhone());
			map.put("amount",person.getAmount());
			data.add(map);
		}
		SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, 
				new String[]{"name","phone","amount"}, new int[]{R.id.name,R.id.phone,R.id.amount});
		listView.setAdapter(adapter);
	}
}